<template>
  <MyDialog
    v-model:visible="DialogVisibleconfig.visible"
    :title="DialogVisibleconfig.title"
    :buttons="DialogVisibleconfig.buttons"
    @close="DialogVisibleconfig.visible = false">
    <!-- 弹窗内容 -->
    <el-form
      :model="Dialogfromdata"
      ref="DialogfromdataRef"
      @submit.prevent
      label-width="70px"
    >
      <el-form-item label="呢称:">
        {{ Dialogfromdata.nickName }}
      </el-form-item>
      <el-form-item prop="" label="头像:">
        <div class="avatar-upload-container">
          <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-change="handleChange"
            accept="image/jpeg,image/png"
            :auto-upload="false"
            :http-request="SubmitAvatarEvent"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </div>
      </el-form-item>
    </el-form>
  </MyDialog>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  onBeforeUnmount,
  watch,
  nextTick,
  getCurrentInstance,
} from "vue";
import { ElMessage, ElIcon } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
const emit = defineEmits(["updateAvatar"]);
const { proxy } = getCurrentInstance();
const api = {
  updateUserAvatar: "updateUserAvatar",
};
const Dialogfromdata = ref({});
const DialogfromdataRef = ref();

const imageUrl = ref("");
const uploadRef = ref(null);
const userAvatarfile = ref({});
const handleAvatarSuccess = (response, uploadFile) => {};

const beforeAvatarUpload = (rawFile) => {
  return true;
};

const handleChange = async (uploadFile) => {
  // 检查文件类型
  console.log("handleChange", uploadFile);

  const isImage = ["image/jpeg", "image/png"].includes(uploadFile.raw.type);
  const isLt2M = uploadFile.raw.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传 JPG/PNG 格式的图片!");
    return false;
  }

  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
    return false;
  }
  userAvatarfile.value = Object.assign({}, uploadFile);
  Dialogfromdata.value.avatar.qqAvatar = userAvatarfile.value.raw;
  // 使用 FileReader 将文件转换为 Base64
  const reader = new FileReader();
  reader.readAsDataURL(uploadFile.raw);

  reader.onload = () => {
    // 创建图片对象验证图片尺寸和比例
    const img = new Image();
    img.onload = () => {
      // 可选：限制最小尺寸
      if (img.width < 100 || img.height < 100) {
        ElMessage.error("图片尺寸太小，请选择至少 100x100 像素的图片");
        return;
      }
      imageUrl.value = reader.result;
    };
    img.src = reader.result;
  };

  reader.onerror = (error) => {
    console.error("Error reading file:", error);
    ElMessage.error("图片读取失败");
  };

  return true;
};

const DialogVisibleconfig = ref({
  visible: false,
  title: "修改头像",
  buttons: [
    {
      text: "取消",
      type: "default",
      click() {
        DialogVisibleconfig.value.visible = false;
      },
    },
    {
      text: "确定",
      type: "primary",
      click() {
        DialogfromdataRef.value.validate((valid) => {
          if (valid) {
            DialogVisibleconfig.value.visible = false;
            SubmitAvatarEvent();
          }
        });
      },
    },
  ],
});
const SubmitAvatarEvent = async () => {
  console.log(userAvatarfile.value.raw);
  // const formData = new FormData();
  // formData.append('avatar', userAvatarfile.value.raw);

  let result = await proxy.request({
    url: api.updateUserAvatar,
    method: "post",
    params: {
      avatar: userAvatarfile.value.raw,
    },
  });
  if (result) {
    proxy.Mymessage.success("修改头像成功");
    DialogVisibleconfig.value.visible = false;
    emit("updateAvatar");
  }
};
const changeshow = (data) => {
  Dialogfromdata.value = Object.assign({}, data);
  console.log(Dialogfromdata.value);

  Dialogfromdata.value.avatar = { userId: data.userId, qqAvatar: data.avatar };
  DialogVisibleconfig.value.visible = true;
};

const triggerUpload = () => {
  uploadRef.value.clearFiles();
  uploadRef.value.handleStart();
  imageUrl.value = "";
};

defineExpose({
  changeshow,
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 200px;
  height: 200px;
  display: block;
  object-fit: contain;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader .el-upload:has(.avatar) {
  border: none;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-upload-container {
  display: flex;
  align-items: center;
  margin-top: 10px;

  border: 1px solid #ccc;
  width: 178px;
  height: 178px;
}

.avatar-upload-container:has(.avatar) {
  border: none;
}
</style>